package code

//短信验证码生成

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"gamesdk/common/aes"
	"time"
)

/*
*验证码
 */
type Code struct {
	Code   string //关键字ID
	Phone  string //电话号码
	Sign   string //签名
	Indate int64  //有效期
	Time   int64  //时间
}

/*
*初始化一个code
 */
func NewCode(code string, phone string, indate int64, sign string, aesKey string) (string, error) {
	c := &Code{
		Code:   code,
		Phone:  phone,
		Sign:   sign,
		Indate: indate,
		Time:   time.Now().Unix(),
	}
	ciphertext, err := c.Encrypt(aesKey)
	if err != nil {
		return "", err
	}
	return ciphertext, nil
}

/*
*验证验证码
 */
func ValidateCode(code string, phone string, sign string, aesKey string) (string, error) {
	c := &Code{}
	err := c.Decrypt(code, aesKey)
	if err != nil {
		return "", errors.New("非法验证码")
	}
	if time.Now().Unix()-c.Time > c.Indate {
		return "", errors.New("验证码已过期")
	}
	if c.Sign != sign {
		return "", errors.New("签名错误")
	}
	if c.Phone != phone {
		return "", errors.New("电话号码不相等")
	}
	return c.Code, nil
}

/*
*加密一个验证码
 */
func (t *Code) Encrypt(aesKey string) (string, error) {
	key := aesKey
	enc := &aes.AesEncrypt{}
	buffer, err := json.Marshal(*t)
	if err != nil {
		return "", err
	}
	src, _ := enc.Encrypt(key, string(buffer))
	encodeString := base64.StdEncoding.EncodeToString(src)
	return encodeString, nil
}

/*
*解密一个验证码
 */
func (t *Code) Decrypt(src string, aesKey string) error {
	decodeBytes, err := base64.StdEncoding.DecodeString(src)
	if err != nil {
		return err
	}
	key := aesKey
	enc := &aes.AesEncrypt{}
	dst, _ := enc.Decrypt(key, decodeBytes)
	e := json.Unmarshal(dst, t)
	if e != nil {
		return e
	}
	return nil
}
